<template>
  <a-row  :gutter="16">
    <a-col  :xs="24" :sm="16">
      <a-card  class="card" size="small" >
        <a-form :layout="queryForm.layout" :model="queryForm" v-bind="formItemLayout">
          <a-form-item label="关键字">
            <a-row :gutter="16">
              <a-col flex="auto">
                <a-input v-model:value="queryForm.searchKey" placeholder="输入关键词" />
              </a-col>
<!--              <a-col>-->
<!--                <a-button type="primary">查询</a-button>-->
<!--              </a-col>-->
              <a-col>
                <a-button @click="clear" type="primary">重置</a-button>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item label="题库">
            <a-radio-group  v-model:value="queryForm.problemType" size="small">
              <a-row :gutter="16">
                <a-col v-for="(item,index) in problemTypeList" :key="index">
                  <a-radio-button :value="item.id">{{item.name}}</a-radio-button>
                </a-col>
              </a-row>
            </a-radio-group>
          </a-form-item>
          <a-form-item label="难度">
            <a-radio-group  v-model:value="queryForm.difficulty" size="small">
              <a-row :span="24" :gutter="16">
                <a-col style="margin-bottom: 5px" v-for="(item,index) in difficultyList" :key="index">
                  <a-radio-button :style="{color : item.icon}" :value="item.id">{{item.name}}</a-radio-button>
                </a-col>
              </a-row>
            </a-radio-group>
          </a-form-item>
          <a-form-item v-show="queryForm.tagIds && queryForm.tagIds.length" label="标签">
            <a-row :span="24" :gutter="5">
              <a-col style="margin-bottom: 5px;cursor: pointer" v-for="item in queryForm.tagIds" :key="item.id">
                <a-tag closable  @close="removeTag(item)" :color="item.color">{{item.name}}</a-tag>
              </a-col>
            </a-row>
          </a-form-item>
        </a-form>
        <a-table
            :scroll="{ x: 750 }"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            :columns="columns"
            :data-source="data"
            :custom-row="opt"
        >
          <template #bodyCell="{ column, text ,record}">
            <template v-if="column.dataIndex === 'title'">
              <a-tooltip placement="top">
                <template #title>
                  {{text}}
                </template>
                <span style="color: #2f6ea7;cursor: pointer" href="#" @click="gotoProblem(record)">{{ text }}</span>
              </a-tooltip>
            </template>
            <template v-if="column.dataIndex === 'difficultyName'">
              <span :style="{color : getDifficultyColor(text)}">{{text}}</span>
            </template>
            <template v-if="column.dataIndex === 'tagNames'">
              <a-row  v-if="showTag" :span="24" :gutter="5">
                <a-col style="margin-bottom: 5px;cursor: pointer" v-for="item in getTags(text)" :key="item.id">
                  <a-tag :color="item.color">{{item.name}}</a-tag>
                </a-col>
              </a-row>
              <span v-else></span>
            </template>
            <template v-if="column.dataIndex === 'passing'">
              <div style="position: relative;top: 10px" >
                <a-progress  :percent="getAcPercent(record.judgeStatusVOS)" size="small"  status="active" />
                <div style="position: absolute;top: -16px;left: 0">
                  <span style="font-size: 16px;margin-left: 20px;font-weight: 600">{{getAcNum(record.judgeStatusVOS)}}</span>
                  <span style="font-size: 12px;">/{{getSubmitNum(record.judgeStatusVOS)}}</span>
                </div>
              </div>
            </template>
<!--            <template v-if="column.dataIndex === 'passing'">-->
<!--              <a-progress  :stroke-color="{'0%': '#108ee9','100%': '#87d068',}" type="circle" :percent="getAcPercent(record.judgeStatusVOS)"   :size="35" >-->
<!--              </a-progress>-->
<!--            </template>-->
          </template>

        </a-table>
      </a-card>
    </a-col>
    <a-col :xs="0" :sm="8"  >
      <a-card  class="card" size="small" title="标签" style="width: 100%;margin-bottom: 5px">
        <template #extra>
          <a style="font-size: 12px" @click="showTag = !showTag">{{showTag ? '隐藏标签' : '显示标签'}}</a>
        </template>
        <a-flex wrap="wrap" :gap="5"  justify="flex-start" align="center">
          <a-tag style="cursor: pointer"  @click="addTag(item)" v-for="item in tagList" :key="item.id" :color="item.color">{{item.name}}</a-tag>
        </a-flex>
      </a-card>
      <a-card  class="card" size="small" :title="onMouseProblemTitle" style="width: 100%;position: sticky;top: 80px">
        <div class="judgeInfo">
          <a-row v-for="item in judgeList">
            <a-col>
              <a-tag :color="item.rgb">{{item.name}}</a-tag>
            </a-col>
            <a-col flex="auto">
              <a-progress :percent="getPercent(item.status)" />
            </a-col>
          </a-row>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>

import {getProblemTypeList} from "@/api/problemType";
import {Difficulty, getDifficultyList} from "@/api/difficulty";
import {getProblemList} from "@/api/problem";
import {getTagList} from "@/api/tag";
import type {Tag} from  "@/api/tag"
import {debounce} from "@/utils/common";
import router from "@/router";
const loading = ref<boolean>(true)
const showTag = ref<boolean>(true)
onMounted(async () => {
  console.log("onMounted")
  problemTypeList.value = (await getProblemTypeList()).data;
  difficultyList.value = (await getDifficultyList()).data;
  tagList.value = (await getTagList()).data;
  tagListCopy.value = [
      ...tagList.value
  ]

  await getProblemList_(queryForm);
})
onActivated(() => {
  console.log("onActivated")
})


//筛选表单
interface FormState {
  layout: 'horizontal' | 'vertical' | 'inline';
  searchKey: string,
  difficulty: string;
  problemType: string;
  tagIds:Array<Tag>,
}
const queryForm = reactive<FormState>({
  layout: 'horizontal',
  searchKey:'',
  difficulty: '',
  problemType: '',
  tagIds:[]
});
const clear = () => {
  queryForm.tagIds = []
  queryForm.difficulty = ''
  queryForm.searchKey = ''
  queryForm.problemType = ''
};
const getProblemListDebounce = debounce(async () => {
  pagination.current = 1
  await getProblemList_(queryForm)
},500,{first : false, end : true})
watch(queryForm, (newVal, oldVal) => {
  getProblemListDebounce()
})
//----------------------------------------------------------------//

//题库
interface ProblemType {
  id: string | number,
  name:string
}
const problemTypeList = ref<ProblemType>()
const getProblemList_ = async (from: FormState) => {
  loading.value = true;
  const data_ = {
    searchKey: from.searchKey,
    difficultyId: from.difficulty,
    problemTypeId: from.problemType,
    tagIds: from.tagIds.map(item => item.id),
  }
  const params = {
    pageNum:pagination.current,
    pageSize:pagination.pageSize
  }
  const res = await getProblemList(data_,params)
  data.value = res.data.rows;
  pagination.total = res.data.total;
  loading.value = false;
}
//----------------------------------------------------------------//


//判题信息
type ProblemJudgeInfo = {
  status:number,
  count:number,
}
const judgeList = Object.values({
  STATUS_ACCEPTED: { status: 0, name: "Accepted",type: 'success', rgb:'#19be6b'},
  STATUS_WRONG_ANSWER: { status: -1, name: "Wrong Answer" ,type: 'error', rgb:'#ed3f14'},
  STATUS_TIME_LIMIT_EXCEEDED: { status: 1, name: "Time Limit Exceeded" ,type: 'error', rgb:'#ed3f14'},
  STATUS_MEMORY_LIMIT_EXCEEDED: { status: 2, name: "Memory Limit Exceeded" , type: 'error', rgb:'#ed3f14'},
  STATUS_COMPILE_ERROR: { status: -2, name: "Compile Error", type: 'warning', rgb:'#f90'},
  STATUS_RUNTIME_ERROR: { status: 3, name: "Runtime Error" , type: 'error', rgb:'#ed3f14'},
})
const onMouseProblemInfo = reactive<Array<ProblemJudgeInfo>>([]);
const onMouseProblemTitle = ref<string>("")
const getPercent = computed(()=>{
  return (status) =>  {
    let obj = onMouseProblemInfo.filter(e => e.status == status) || [{status : status ,count : 0}]
    if(obj.length == 0)
      obj = [{status : status ,count : 0}]
   return Math.floor((obj[0].count / onMouseProblemInfo.map(item => item.count).reduce((accumulator, currentValue) => accumulator + currentValue, 0)) * 100);
  }
})
const getAcPercent = (judgeInfos : Array<ProblemJudgeInfo>) => {
  return Math.floor((getAcNum(judgeInfos) /  getSubmitNum(judgeInfos)) * 100);
}
const getSubmitNum = (judgeInfos : Array<ProblemJudgeInfo>) : number => {
  return judgeInfos.map(item => item.count).reduce((accumulator, currentValue) => accumulator + currentValue, 0)
}
const getAcNum = (judgeInfos : Array<ProblemJudgeInfo>) : number => {
  let list = judgeInfos.filter(e => e.status == 0)
  if(list.length == 0)
    list = [{status : 0 ,count : 0}]
  return list[0].count
}
//----------------------------------------------------------------//


//难度
const difficultyList = ref<Array<Difficulty>>();
const getDifficultyColor = computed(() => {
  return (name:string) => {
    const names = difficultyList.value?.filter(item => item.name === name);
    return names && names.length ? names[0].icon : "";
  }
})
//----------------------------------------------------------------//


//标签
const tagListCopy = ref<Array<Tag>>();
const tagList = ref<Array<Tag>>();
const formItemLayout = computed(() => {
  const { layout } = queryForm;
  return layout === 'horizontal'
      ? {
        wrapperCol: { span: 22 },
      }
      : {};
});
const addTag = (item:Tag) =>{

  tagList.value = tagList.value?.filter(e => e.id !=item.id);
  queryForm.tagIds.push(item);
}
const removeTag = (item : Tag) =>{
  console.log(item.id)
  const res = queryForm.tagIds.filter(e => e.id !=item.id)
  queryForm.tagIds = res;
  console.log(queryForm.tagIds)
  tagList.value.push(item)
}
const getTags = computed(() =>{
  return (tagNames :string) => {
    if(tagNames == null)
        return []
    const tagNameList = tagNames.split(',');
    const res = tagListCopy.value?.filter(item => tagNameList.includes(item.name));
    return res ? res : []
  }
})
//----------------------------------------------------------------//



//表结构
const data = ref();
const columns = [
  {
    title: '编号',
    dataIndex: 'problemId',
    key: 'problemId',
  },
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    width: 250,
    ellipsis: true
  },
  {
    title: '难度',
    dataIndex: 'difficultyName',
    key: 'difficultyName',
  },
  {
    title: '标签',
    dataIndex: 'tagNames',
    key: 'tagNames',
    ellipsis: true,
    width:250
  },
  {
    title: '通过率',
    dataIndex: 'passing',
    key: 'passing',
    width:110,
    ellipsis: true,
  }
];
const pagination = reactive({
  total: 200,
  current: 1,
  pageSize: 10,
  pageSizeOptions:['5', '10', '15', '20']
});
const handleTableChange = (p, filters, sorter) => {
  pagination.current = p.current
  pagination.pageSize= p.pageSize
  getProblemList_(queryForm)
}
const gotoProblem = (e) =>{
  // console.log(e)
  router.push(`/problem/${e.id}`);
}
const opt = (record) => {
  return {
    onClick: (event) => {
      // console.log(event)
    },       // 点击行
    onDblclick: (event) => {},
    onContextmenu: (event) => {},
    onMouseenter: (event) => {
      // console.log(event)
      console.log(record)
      onMouseProblemInfo.length = 0
      Object.assign(onMouseProblemInfo,record.judgeStatusVOS)
      onMouseProblemTitle.value = record.title

    },  // 鼠标移入行
    onMouseleave: (event) => {

    }
  };
}
//----------------------------------------------------------------//

</script>
<style scoped lang="scss">
.judgeInfo{
  .ant-row{
    margin: 15px 0;
  }
}
</style>
